package com.wt.wechatTools;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.wt.wechatTools.room.WorkRepository;
import com.wt.wechatTools.tools.MyRequest;

import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class FragmentCdk extends Fragment {
    private static final String TAG = "FragmentPay";
    private Button btnCDK;
    private WorkRepository workRepository;
    private EditText editCDK;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View viewPay = inflater.inflate(R.layout.fragment_cdk, container, false);
        workRepository = new WorkRepository(getContext());

        btnCDK = viewPay.findViewById(R.id.btnCDK);
        editCDK = viewPay.findViewById(R.id.editCDK);

        /**
         * 通过cdk充值 更新用户endTime
         */
        btnCDK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭软键盘
                hintKeyBoard();
                if (editCDK.getText().toString().isEmpty()) {
                    Toast.makeText(v.getContext(), "请输入CDK！", Toast.LENGTH_SHORT).show();
                    return;
                }
                //开启线程
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        RequestBody requestBody = new FormBody.Builder()
                                .add("cdk", editCDK.getText().toString())
                                .build();
                        Request request = new Request.Builder()
                                .url(MyRequest.proUrl + "chekCdk")
                                .post(requestBody)
                                //增加关闭连接，不让它保持连接：https://blog.csdn.net/zhangteng22/article/details/52233126
                                .addHeader("Connection", "close")
                                .build();
                        Response res = null;
                        try {
                            res = okHttpClient.newCall(request).execute();
                            if (res.isSuccessful()) {
                                final String jsonString = res.body().string();
                                JSONObject jsonObject = new JSONObject(jsonString);
                                String endTimeString = jsonObject.getString("endTime");
                                //更新数据库
                                workRepository.updateUserEndTime(endTimeString);
                                Looper.prepare();
                                Toast.makeText(v.getContext(), "CDK验证成功！", Toast.LENGTH_SHORT).show();
                                //页面跳转
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        NavController nv = Navigation.findNavController(v);
                                        nv.navigate(R.id.fragmentHome);
                                    }
                                });
                                Looper.loop();
                            } else {
                                Looper.prepare();
                                Toast.makeText(v.getContext(), "CDK不正确！", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        } catch (Exception e) {
                            Log.d(TAG, "run: " + e);
                        } finally {
                            res.close();
                        }
                    }
                }).start();
            }
        });
        return viewPay;
    }

    /**
     * 关闭软键盘
     */
    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getContext().INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getActivity().getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getActivity().getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

}